package com.phamkhanh.dao;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;

public abstract class GenericDAOImpl<T, ID extends Serializable> implements GenericDAO<T, ID> {
	private SessionFactory sessionFactory;
	
	@Autowired
	@Required
	public void setSessionFactory(SessionFactory sessionFactory){
		this.sessionFactory = sessionFactory;
	}
	
	public Session getSession(){
		return sessionFactory.getCurrentSession();
	}

	@Override
	public void save(T entity) {
		getSession().saveOrUpdate(entity);
	}

	@Override
	public void merge(T entity) {
		getSession().merge(entity);
	}

	@Override
	public void delete(T entity) {
		getSession().delete(entity);
	}

	@Override
	public List<T> findMany(Query query) {
		return (List<T>)query.list();	
	}

	@Override
	public T findOne(Query query) {
		T t = (T) query.uniqueResult();
		return t;
	}

	@Override
	public List<T> findAll(Class<T> clazz) {
		List<T> list =null;
		Query query = getSession().createQuery("from " + clazz.getName());
		list = (List<T>)query.list();
		return list;
	}

	@Override
	public T findById(Class<T> clazz, ID id) {
		T t = (T)getSession().get(clazz, id);
		return t;
	}
}
